package blue.webserver;

import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;

import blue.logger.JsonTransform;

public class ChatMessageHandler implements HttpHandler{
	ZmqPublisher slave_send_;
	ZmqSubscriber slave_recv_;
	
	public ChatMessageHandler(ZmqPublisher slave_send, ZmqSubscriber slave_recv) {
		slave_send_ = slave_send;
		slave_recv_ = slave_recv;
	}

	/* Parse a string into a map. */
	public Map<String, String> queryToMap(String query) {
		/* Input: var1=val1&var2=val2 */
	    Map<String, String> result = new HashMap<String,String>();
	    for (String param : query.split("&")) {
	        String[] entry = param.split("=");
	        if (entry.length > 1) {
	            result.put(entry[0], entry[1]);
	        }else{
	            result.put(entry[0], "");
	        }
	    }
	    return result;
	}

	private ArrayList<String> readAllWithNonblocking(ArrayList<String> list) {
		while(true) {
			String recv_str = slave_recv_.recv();
			if (recv_str==null) break;
			list.add(recv_str);
		}
		return list;
	}
	
	private ArrayList<String> readAll(ArrayList<String> list){
		String recv_data = slave_recv_.recvWithBlocking();
		list.add(recv_data);
		return readAllWithNonblocking(list);
	}
	
	@Override
	public void handle(HttpExchange exchange) throws IOException {
		String send_command = exchange.getRequestURI().getQuery();
		// Recv buff message
		ArrayList<String> recv_list = new ArrayList<String>();
		recv_list = readAllWithNonblocking(recv_list);
		// Send Message to master
		slave_send_.publish(send_command);
		// Wait for its response
		recv_list = readAll(recv_list);
		if (!recv_list.isEmpty()) {
			String rep_data = JsonTransform.toJson(recv_list);
			
	        exchange.sendResponseHeaders(200, 0);
	        OutputStream os = exchange.getResponseBody();
	        os.write(rep_data.getBytes());
	        os.close();
		}else {
			System.out.println("This should never be arrived.");
		}
	}
}
